package com.ding.controller;

import com.ding.service.RuleService;
import org.drools.template.DataProvider;
import org.drools.template.DataProviderCompiler;
import org.drools.template.objects.ObjectDataProvider;
import org.drools.template.parser.DefaultTemplateContainer;
import org.kie.api.builder.Results;
import org.kie.api.io.ResourceType;
import org.kie.internal.utils.KieHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.util.Assert;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ding
 * @date 2021/6/9 14:31
 */

@RestController
@RequestMapping("template")
public class TemplateController {

    @Autowired
    private RuleService ruleService;

    @PostMapping
    public Results createRule(String operator, String doing) {
        DataProviderCompiler converter = new DataProviderCompiler();
        InputStream inputStream = this.getClass().getResourceAsStream("/template.drl");
        DefaultTemplateContainer container = new DefaultTemplateContainer(inputStream);
        Assert.notNull(inputStream, "读取模板失败！");
        ArrayList<Map<String, String>> arrayList = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();
        map.put("condition", operator);
        map.put("execution", doing);
        map.put("clazz", "People");
        arrayList.add(map);
        DataProvider data = new ObjectDataProvider(container, arrayList);
        String drl = converter.compile(data, "/template.drl");
        KieHelper kieHelper = new KieHelper();
        kieHelper.addContent(drl, ResourceType.DRL);
        ruleService.addRule(drl);
        return kieHelper.verify();
    }
}
